package cn.lingyangwl.agile.msg.push.manager;

import cn.lingyangwl.agile.model.BasePlusPO;
import cn.lingyangwl.agile.msg.push.mapper.ReceiverMapper;
import cn.lingyangwl.agile.msg.push.mapper.ReceiverSubscribeMapper;
import cn.lingyangwl.agile.msg.push.model.entity.Receiver;
import cn.lingyangwl.agile.msg.push.model.entity.ReceiverSubscribe;
import cn.lingyangwl.framework.tool.core.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 接收者订阅的推送 仓储层
 *
 * @author shenguangyang
 */
@Slf4j
@Repository
public class ReceiverSubscribeManager extends ServiceImpl<ReceiverSubscribeMapper, ReceiverSubscribe>
    implements IService<ReceiverSubscribe> {
    @Resource
    private ReceiverMapper receiverMapper;

    public List<Receiver> listMsgSubscriber(Long noticeId) {
        // 一般指定的任务接收人不会太多, 所以这里直接采用in语法
        LambdaQueryWrapper<ReceiverSubscribe> lqw = ReceiverSubscribe.lqw().eq(ReceiverSubscribe::getNoticeId, noticeId);
        List<Long> receiverIds = this.list(lqw).stream().map(ReceiverSubscribe::getReceiverId).distinct()
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(receiverIds)) {
            return Collections.emptyList();
        }

        LambdaQueryWrapper<Receiver> receiverLqw = Receiver.lqw().in(Receiver::getId, receiverIds)
                .orderByDesc(BasePlusPO::getCreatedAt);
        return receiverMapper.selectList(receiverLqw);
    }
}
